#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "weather_api.hpp"
#include "my_tft.hpp"
#include "display.hpp"
const char *API_URL =
  "https://api.caiyunapp.com/v2.6/7ylocdmwZjQL1Gct/104.102289,30.674422/realtime";

WeatherNow now;

bool fetchWeather() {
  HTTPClient http;
  http.begin(API_URL);
  int code = http.GET();
  if (code != 200) { http.end(); return false; }

  DynamicJsonDocument doc(16 * 1024);
  DeserializationError err = deserializeJson(doc, http.getStream());
  http.end();
  if (err) return false;

  JsonObject rt = doc["result"]["realtime"];
  now.temp      = rt["temperature"].as<float>();
  now.humidity  = rt["humidity"].as<float>();
  now.sky       = rt["skycon"].as<const char*>();
  now.apparent  = rt["apparent_temperature"].as<float>();
  now.aqi       = rt["air_quality"]["aqi"]["chn"].as<int>();
  now.comfort   = rt["life_index"]["comfort"]["desc"].as<const char*>();
  return true;
}

void initweather() {
  if (fetchWeather()) showWeather();
  else                tft_display_text("API ERROR", 0, 0, ST77XX_RED, 2);
}

void updateWeather() {
  static uint32_t last_weather = 0;
  static const uint32_t PERIOD_weather = 30 * 60 * 1000UL;  // 30分钟

  if (millis() - last_weather > PERIOD_weather) {
    if (fetchWeather()) showWeather();
    last_weather = millis();
  }
}